﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Collections;
using System.Configuration;
using System.Net;

namespace WorkStation.Frameworks.Core.Web
{
    public class MailTool
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public string From { get; set; }
        public string SmtpServer { get; set; }

        public MailTool(string userName, string password, string from, string smtpServer) 
        {
            this.UserName = userName;
            this.Password = password;
            this.From = from;
            this.SmtpServer = smtpServer;
        }

        public string SendExternalMail(string[] SendTo, string[] CopyTo, string[] BlindCopyTo, string Subject, string Body, Hashtable fileTable) 
        {
            try
            {
                MailMessage mail = new MailMessage();

                if (SendTo != null)
                {
                    foreach (string address in SendTo)
                    {
                        mail.To.Add(address);
                    }
                }

                if (CopyTo != null)
                {
                    foreach (string address in CopyTo)
                    {
                        mail.CC.Add(address);
                    }
                }

                if (BlindCopyTo != null)
                {
                    foreach (string address in BlindCopyTo)
                    {
                        mail.Bcc.Add(address);
                    }
                }

                mail.Body    = Body;
                mail.Subject = Subject;
                mail.From    = new MailAddress(this.From);

                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.IsBodyHtml = true;

                if (fileTable != null && fileTable.Count != 0) 
                {
                    foreach (string key in fileTable.Keys) 
                    {
                        System.Net.Mail.Attachment attachment = new Attachment(fileTable[key].ToString());
                        attachment.Name = key;

                        mail.Attachments.Add(attachment);
                    }
                }

                SmtpClient client = new SmtpClient(this.SmtpServer);

                client.EnableSsl = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Credentials = new NetworkCredential(this.UserName, this.Password);

                client.Send(mail);

                foreach (Attachment attachment in mail.Attachments) 
                {
                    attachment.Dispose();
                }
            }
            catch (Exception ce) 
            {
                return "FALSE^" + ce.ToString();
            }

            return "TRUE^";
        }
    }
}
